//
//  SupplyAndDemandListVC.m
//  phmall
//
//  Created by admin on 2017/11/15.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "SupplyAndDemandListVC.h"
#import "SupplyAndDemandDetailsVC.h"
//#import "SupplyAndDemandListView.h"
#import "SupplyAndDemandModel.h"
#import "SupplyAndDemandCell.h"
@interface SupplyAndDemandListVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    UIImageView *head;
    UIView *headerView;
    NSInteger    start;
    NSInteger    count;
}
@property(nonatomic,strong)MBProgressHUD *hud;
@property(strong,nonatomic)NSMutableArray *SupplyArray;
@property(strong,nonatomic)NSString *pic;
@property(strong,nonatomic)NSString *url;
@end

@implementation SupplyAndDemandListVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (self.emptyType==EmptyDataSetNoNetwork) {
        start=0;
        [self loadDataWithget_ad:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view).priorityHigh();
        make.bottom.equalTo(self.view).with.offset(0);
    }];
    count=0;
    if (@available(iOS 11.0, *)) {
        self.myTableview.estimatedRowHeight = 0;
        self.myTableview.estimatedSectionFooterHeight = 0;
        self.myTableview.estimatedSectionHeaderHeight = 0;
        self.myTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    
    head=[[UIImageView alloc]init];
    [headerView addSubview:head];
    [head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
        make.height.offset(200);
    }];
    
    [self loadDataWithget_ad:YES];
    self.myTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    self.myTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
    self.myTableview.mj_footer.hidden=YES;
    // Do any additional setup after loading the view.
}
-(void)HeaderRefresh{
    start=0;
    [self loadDataWithget_ad:NO];
}
-(void)footeRefresh{
    start=self.SupplyArray.count;
    if (start<count) {
        [self loadDataWithget_ad:YES];
    }else{
        [self.myTableview.mj_footer endRefreshingWithNoMoreData];
    }

 
}
- (void)loadDataWithget_ad:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"supply/get_ad"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
           
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableDictionary *data=responseDict[@"data"];
                self.pic=[NSString stringWithFormat:@"%@%@",IMGURL,data[@"default_wap_supply"][@"pic"]];
            }
            if ([self.type isEqualToString:@"suppy"]) {
                [self loadDataWithSupply:reload];
            }else{
                [self loadDataWithBuy:reload];
            }
        }
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        [self.myTableview setTableHeaderView:nil];
        self.myTableview.mj_footer.hidden=YES;
        [self.SupplyArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
    }];
}
- (void)loadDataWithSupply:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"supply"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"start"];
    [parametersDic setObject:self.uid forKey:@"type"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.SupplyArray removeAllObjects];
            [self.myTableview setTableHeaderView:nil];
            self.myTableview.mj_footer.hidden=YES;
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            count=[responseDict[@"count"] intValue];
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.myTableview.mj_header endRefreshing];
                [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.myTableview reloadData];
                }
            }else{
                 [self analysisDataWithOnsaleArray:data];
            }
        }
    } andFailure:^{
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
    }];
}
- (void)loadDataWithBuy:(BOOL)reload{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"supply/buy"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"start"];
    [parametersDic setObject:self.uid forKey:@"type"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.SupplyArray removeAllObjects];
            [self.myTableview setTableHeaderView:nil];
            self.myTableview.mj_footer.hidden=YES;
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            count=[responseDict[@"count"] intValue];
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.myTableview.mj_header endRefreshing];
                [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.myTableview reloadData];
                }
            }else{
                [self analysisDataWithOnsaleArray:data];
            }
        
        }

    } andFailure:^{
    
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
    }];
}

- (void)analysisDataWithOnsaleArray:(NSMutableArray *)array{
    for (NSDictionary *dict in array) {
        SupplyAndDemandModel *model = [SupplyAndDemandModel yy_modelWithDictionary:dict];
        [self.SupplyArray addObject:model];
    }

    if (self.SupplyArray.count!=0) {
       
        //数量少于2条时隐藏上拉加载
        if (self.SupplyArray.count<2) {
            self.myTableview.mj_footer.hidden=YES;
        }else{
            self.myTableview.mj_footer.hidden=NO;
        }
        if (self.pic!=nil&&self.pic.length!=0) {
            [head sd_setImageWithURL:[NSURL URLWithString:self.pic] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
        }
        CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        CGRect frame = headerView.bounds;
        frame.size.height = height;
        headerView.frame = frame;
        [self.myTableview setTableHeaderView:headerView];
        
    }else{
        //数量为0条时隐藏上拉加载
        self.myTableview.mj_footer.hidden=YES;
    }
    [self.myTableview reloadData];
    [self.myTableview.mj_header endRefreshing];
    [self.myTableview.mj_footer endRefreshing];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.SupplyArray.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SupplyAndDemandCell *cell=[SupplyAndDemandCell theShareCellWithTableView:tableView];
    SupplyAndDemandModel *model=self.SupplyArray[indexPath.row];
    NSLog(@"%ld",(long)indexPath.row);
    cell.model=model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SupplyAndDemandModel *model=self.SupplyArray[indexPath.row];
    if (self.delegate &&[self.delegate respondsToSelector:@selector(didSelectRowAtIndexPath:)]) {
        [self.delegate didSelectRowAtIndexPath:model.uid];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"分类缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return - 22;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"当前分类暂无信息！"),Localized(@"先去其他地方逛逛吧。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"当前分类暂无信息！") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"当前分类暂无信息！") length], [Localized(@"先去其他地方逛逛吧。") length])];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    start=0;
    [self loadDataWithget_ad:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource = self;
        _myTableview.emptyDataSetDelegate = self;
    }
    return _myTableview;
}
-(NSMutableArray *)SupplyArray{
    if (!_SupplyArray) {
        _SupplyArray=[[NSMutableArray alloc]init];
    }
    return _SupplyArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
